package logic

import (
	"context"

	"go-zero-mall/app/admin/cmd/rpc/internal/svc"
	"go-zero-mall/app/admin/cmd/rpc/pd"

	"github.com/jinzhu/copier"
	"github.com/zeromicro/go-zero/core/logx"
)

type RoleListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRoleListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RoleListLogic {
	return &RoleListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 角色-列表
func (l *RoleListLogic) RoleList(in *pd.UmsRoleListReq) (*pd.UmsRoleListResp, error) {
	countBuilder := l.svcCtx.UmsRoleModel.CountBuilder("*")

	rowBuilder := l.svcCtx.UmsRoleModel.RowBuilder()
	if len(in.Keyword) > 0 {
		countBuilder = countBuilder.Where("name like ?", in.Keyword+"%")
		rowBuilder = rowBuilder.Where("name like ?", in.Keyword+"%")
	}

	d, err := l.svcCtx.UmsRoleModel.FindByPage(l.ctx, rowBuilder, in.PageNum, in.PageSize)
	if err != nil {
		return nil, err
	}
	var resp []*pd.UmsRoleCreateReq
	for _, role := range d {
		var resp1 pd.UmsRoleCreateReq
		_ = copier.Copy(&resp1, role)
		resp1.CreateTime = role.CreateTime.Time.Unix()
		resp = append(resp, &resp1)
	}
	total, err := l.svcCtx.UmsRoleModel.FindCount(l.ctx, countBuilder)
	if err != nil {
		return nil, err
	}
	return &pd.UmsRoleListResp{List: resp, Total: total}, nil
}
